
import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TextArea;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;

import org.apache.log4j.Logger;

import dsmflex.taskengine.DsmflexStartTaskEngineMain;

import test.taskengine.StartTaskEngineMain;


public class TaskEngineSystemTray extends java.awt.Frame implements Runnable {

	private static final long serialVersionUID = -6498919258631774008L;
	
	private static Logger log = Logger.getLogger(TaskEngineSystemTray.class);

	private static final String COMMAND_SHOW_CONSOLE = "任务引擎监控";
	private static final String COMMAND_EXIT = "退出";

	private static final int MAX_ROW = 100;

	private TextArea txtOutput = new TextArea();
	private TrayIcon trayIcon;

	private PipedInputStream pipedOutIn;
	private PipedInputStream pipedErrIn;
	
	private DsmflexStartTaskEngineMain stem = null;
	
	private Thread systemTrayThread = null;

	public TaskEngineSystemTray() {
		super();
		initForm();
		initSystemTray();
		//stem = new StartTaskEngineMain();
		stem = new DsmflexStartTaskEngineMain();
		
		pipedOutIn = new PipedInputStream();
		pipedErrIn = new PipedInputStream();

		try {
			System.setOut(new PrintStream(new PipedOutputStream(pipedOutIn), true));
			System.setErr(new PrintStream(new PipedOutputStream(pipedErrIn), true));
		} catch (IOException e) {
			e.printStackTrace();
		}

		systemTrayThread = new Thread(this);
		systemTrayThread.start();
	}

	@Override
	public void run() {

		BufferedReader systemOutIn = new BufferedReader(new InputStreamReader(pipedOutIn));
		BufferedReader systemErrIn = new BufferedReader(new InputStreamReader(pipedErrIn));

		int row = 0;
		while (true) {
			try {
				if (systemOutIn.ready()) {
					row++;
					if (row > MAX_ROW) {
						row = 0;
						txtOutput.setText("");
					}
					String text = systemOutIn.readLine();

					txtOutput.append("\n");
					txtOutput.append(text);
				}

				if (systemErrIn.ready()) {
					row++;
					if (row > MAX_ROW) {
						row = 0;
						txtOutput.setText("");
					}
					String text = systemErrIn.readLine();

					txtOutput.append("\n");
					txtOutput.append(text);
				}

			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private void showWindow() {
		this.setVisible(true);
	}

	private void hideWindow() {
		this.setVisible(false);
	}

	
	private void initForm() {
		txtOutput.setEditable(false);
		txtOutput.setForeground(Color.white);
		txtOutput.setBackground(Color.black);

		this.setLayout(new BorderLayout());
		this.add(txtOutput, BorderLayout.CENTER);

		this.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				hideWindow();
			}
		});
		Image image = Toolkit.getDefaultToolkit().getImage(TaskEngineSystemTray.class.getClass().getResource("/monitor.png"));
		//ImageIcon image=new   ImageIcon(TaskEngineSystemTray.class.getClass().getResource("/monitor.png"));
		this.setIconImage(image);
	}

	public void initSystemTray() {
		Image image = Toolkit.getDefaultToolkit().getImage(TaskEngineSystemTray.class.getClass().getResource("/monitor.png"));
		//ImageIcon image=new   ImageIcon(TaskEngineSystemTray.class.getClass().getResource("/monitor.png"));
		trayIcon = new TrayIcon(image);
		trayIcon.setImageAutoSize(true);

		if (SystemTray.isSupported()) {
			SystemTray tray = SystemTray.getSystemTray();
			if (tray != null) {
				try {
					tray.add(trayIcon);
				} catch (AWTException e1) {
					e1.printStackTrace();
				}
			}
			
			
			PopupMenu popupMenu = new PopupMenu();

			MenuItem mnuItem = new MenuItem("显示控制台");
			final MenuItem startRunTask = new MenuItem("开始运行");
			final MenuItem stopRunTask = new MenuItem("停止运行");
			final MenuItem suspendRunTask = new MenuItem("暂停运行");
			final MenuItem reRunTask = new MenuItem("恢复运行");
			
			startRunTask.setEnabled(true);
			stopRunTask.setEnabled(false);
			suspendRunTask.setEnabled(false);
			reRunTask.setEnabled(false);
			trayIcon.setToolTip("任务引擎监控");
			ActionListener actionListener = new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					try {
					String ac = e.getActionCommand();
					if (ac.equalsIgnoreCase(COMMAND_SHOW_CONSOLE)) {
						showWindow();
					} else if (ac.equalsIgnoreCase(COMMAND_EXIT)) {
						exitApp();
						stem.stopRunTask();
					}else if (ac.equalsIgnoreCase("0")) {
						stopRunTask.setEnabled(false);
						stopRunTask.setLabel("正在停止..");
						systemTrayThread.sleep(1000);
						stopRunTask.setLabel("停止运行");
						reRunTask.setEnabled(false);
						suspendRunTask.setEnabled(false);
						startRunTask.setEnabled(true);
						stem.stopRunTask();//停止
					}else if (ac.equalsIgnoreCase("1")) {
						startRunTask.setEnabled(false);
						reRunTask.setEnabled(false);
						suspendRunTask.setEnabled(true);
						stopRunTask.setEnabled(true);
						stem.startRunTask();//开始
					}else if (ac.equalsIgnoreCase("2")) {
						suspendRunTask.setEnabled(false);
						startRunTask.setEnabled(false);
						reRunTask.setEnabled(true);
						stopRunTask.setEnabled(true);
						stem.suspendRunTask();//暂停
					}else if (ac.equalsIgnoreCase("3")) {
						reRunTask.setEnabled(false);
						startRunTask.setEnabled(false);
						suspendRunTask.setEnabled(true);
						stopRunTask.setEnabled(true);
						stem.reRunTask();//恢复
					}
					
					} catch (Exception e2) {
						
					}
				}
			};
	
			
			mnuItem.setActionCommand(COMMAND_SHOW_CONSOLE);
			mnuItem.addActionListener(actionListener);
			popupMenu.add(mnuItem);

			
			startRunTask.setActionCommand("1");
			startRunTask.addActionListener(actionListener);
			popupMenu.add(startRunTask);
			
			
			stopRunTask.setActionCommand("0");
			stopRunTask.addActionListener(actionListener);
			popupMenu.add(stopRunTask);
			
			
			suspendRunTask.setActionCommand("2");
			suspendRunTask.addActionListener(actionListener);
			popupMenu.add(suspendRunTask);
			
			
			reRunTask.setActionCommand("3");
			reRunTask.addActionListener(actionListener);
			popupMenu.add(reRunTask);
			
			
			
			popupMenu.addSeparator();

			mnuItem = new MenuItem("退出");
			mnuItem.setActionCommand(COMMAND_EXIT);
			mnuItem.addActionListener(actionListener);
			popupMenu.add(mnuItem);

			trayIcon.setPopupMenu(popupMenu);
		}
	}

	private void exitApp() {
		if (trayIcon != null) {
			SystemTray.getSystemTray().remove(trayIcon);
		}
		System.exit(0);
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		TaskEngineSystemTray tray = new TaskEngineSystemTray();
		tray.setTitle("任务监控");
		tray.setSize(640, 480);

	}
}
